﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QRCode2.Models;
using System.Web.Security;
using WebMatrix.WebData;

namespace QRCode2.Controllers
{
    public class UserController : Controller
    {
        public UserDBContext db = new UserDBContext();
        public AgentQRCodeDBContext dbag = new AgentQRCodeDBContext();
        private AgentCommentDBContext dbComment = new AgentCommentDBContext();

        //
        // GET: /User/

        [Authorize(Roles = "Administrator")]
        public ActionResult Index()
        {
            return View(db.Users.ToList());
        }

        //
        // GET: /User/Details/5

        
        public ActionResult Details(int id = 0)
        {
            string agentQRCode = "";
            string addComment = "N";
            string agentUserName = "";

            if (Request.QueryString["un"] != "")
            {
                agentUserName = Request.QueryString["un"];

                if (agentUserName == null)
                    agentUserName = "";
            }
            
            
            if (Request.QueryString["agentqr"] != "")
            {
                agentQRCode = Request.QueryString["agentqr"];
            }

            //if (Session.Count > 0 && Session["AgentQRCode"].ToString() != null)

            if (Session.Count > 0 && Session["AgentQRCode"] != null)
            {
                agentQRCode = Session["AgentQRCode"].ToString();
                addComment = "Y";
            }

            User user = new User();

            if (id > 0)
            {
                user = db.Users.Find(id);
            }
            else if (agentUserName != "")
            {
                user = db.Users.Where(b => b.UserName == agentUserName).ToList()[0];

                //Assign SessionQRCode
                var agentQR = dbag.AgentQRCodes.Where(b => b.AgentUserName == agentUserName).ToList()[0];

                Session["AgentQRCOde"] = agentQR.Code;

            }
            else if (agentQRCode != "")
            {
                Session["AgentQRCOde"] = agentQRCode;

                var userQRCodes = dbag.AgentQRCodes.Where(b => b.Code == agentQRCode).ToList();

                if (userQRCodes.Count == 1)
                {
                    var agent = userQRCodes[0];
                    user = db.Users.Where(b => b.UserName == agent.AgentUserName).ToList()[0];
                }
            }

            if (user == null)
            {
                return HttpNotFound();
            }

            string imageLocation = ("~/Images/User/") + user.Picture.ToString();

            ViewBag.Picture = imageLocation;

            String comment = Request.Form["commentToAgent"];

            if (addComment == "Y")
            {

                //Add comment inside agent
                AgentComment ac = new AgentComment();
                ac.UserName = User.Identity.Name;
                ac.AgentUserName = user.UserName;
                ac.Comment = comment;
                ac.CommentTime = DateTime.Now;
                ac.QRCode = agentQRCode;
                ac.Active = true;

                dbComment.AgentComments.Add(ac);
                dbComment.SaveChanges();

                ViewBag.CommentSend= "Your Comment has been sent to Agent!";
            }

            return View(user);
        }

 

        //
        // GET: /User/Create

        [Authorize(Roles = "Administrator")]
        public ActionResult Create()
        {
            List<SelectListItem> allRoles = new List<SelectListItem>();

            allRoles.Add(new SelectListItem
            {
                Text = "Administrator",
                Value = "Administrator"
            });
            allRoles.Add(new SelectListItem
            {
                Text = "RealEstateAgent",
                Value = "RealEstateAgent",
                Selected = true
            });
            allRoles.Add(new SelectListItem
            {
                Text = "HomeBuyer",
                Value = "HomeBuyer"
            });

            ViewBag.ddRoles = allRoles;

            return View();
        }

        //
        // POST: /User/Create

        [HttpPost]
        //[Authorize(Roles = "Administrator")]
        public ActionResult Create(User user)
        {


            if (ModelState.IsValid)
            {

                string RoleName = Request.Form.GetValues("ddRoles")[0];

                user.CompanyID = 1;
                user.Active = true;
                user.Picture = "default.jpg";
                user.UserType = RoleName;
                db.Users.Add(user);
                db.SaveChanges();

                //Insert record inside UserProfile
                WebSecurity.CreateUserAndAccount(user.UserName, "temppass");

                //Insert record inside dbo.webpages_Roles
                Roles.AddUserToRole(user.UserName, RoleName);

                //For RealEstateAgent create record inside AgentQRCodes
                if (RoleName == "RealEstateAgent")
                {
                    AgentQRCode agent = new AgentQRCode();
                    agent.AgentUserName = user.UserName;
                    agent.Active = true;
                    dbag.AgentQRCodes.Add(agent);
                    dbag.SaveChanges();
                }

                return RedirectToAction("Index");
            }


            return View();
        }

        //
        // GET: /User/Edit/5

        [Authorize]
        public ActionResult Edit(int id = 0)
        {
            User user = db.Users.Find(id);

            if (user == null)
            {
                if (User.Identity.Name != "admin")
                {
                    var users = db.Users.Where(b => b.UserName == User.Identity.Name).ToList();

                    if (users.Count == 1)
                        user = users[0];

                    if (user == null)
                    {
                        user = new User();
                        user.UserName = User.Identity.Name;
                        user.CompanyID = 1;
                        user.Active = true;
                        user.Picture = "default.jpg";
                        db.Users.Add(user);
                        db.SaveChanges();
                    }

                }
            }

            if (user == null)
            {
                return HttpNotFound();
            }

            ViewBag.UserName = user.UserName;

            //Set picture location
            //string imageLocation = Server.MapPath("~/Images/User/") + user.Picture.ToString() + ".jpg";
            string imageLocation = ("~/Images/User/") + user.Picture.ToString();

            ViewBag.Picture = imageLocation;

            return View(user);
        }


        //
        // POST: /User/Edit/5

        [HttpPost]
        //[ValidateAntiForgeryToken]
        [Authorize]
        public ActionResult Edit(User user, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {

                String pic = Request.Form["Picture"];
                String userType = Request.Form["UserType"];

                //Save picture if file exists

                if (file != null)
                {
                    Guid guid = Guid.NewGuid();

                    string imageLocation = Server.MapPath("~/Images/User/") + guid.ToString() + ".jpg";

                    file.SaveAs(imageLocation);

                    user.Picture = guid.ToString() + ".jpg";
                }
                else
                {
                    user.Picture = pic;
                }

                user.CompanyID = 1;
                user.UserType = userType;
                user.Active = true;

                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();

                if (User.Identity.Name == "admin")
                    return RedirectToAction("Index");
                else
                    return RedirectToAction("Index", "Home", null);
            }
            return View(user);
        }

        //
        // GET: /User/Delete/5

        [Authorize(Roles = "Administrator")]
        public ActionResult Delete(int id = 0)
        {
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        //
        // POST: /User/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Administrator")]
        public ActionResult DeleteConfirmed(int id)
        {
            User user = db.Users.Find(id);
            db.Users.Remove(user);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}